package com.golden.procedure.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.golden.procedure.activiti.client.activitiClientAPI;
import com.golden.procedure.dao.WorkOrderMapper;
import com.golden.procedure.dao.WorkOrderPhotographyMapper;
import com.golden.procedure.domain.WorkCommentDO;
import com.golden.procedure.domain.WorkOrderDO;
import com.golden.procedure.domain.WorkTaskHistoryDO;
import com.golden.procedure.entity.WorkOrder;
import com.golden.procedure.entity.WorkOrderExample;
import com.golden.procedure.query.WorkOrderQueryDO;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.ResultSupport;
import com.golden.procedure.service.IWorkOrderService;
import com.golden.procedure.util.BeanUtilsExtends;
import com.golden.procedure.util.BonConstant;
import com.golden.procedure.util.TaskDefKey;

@Service("workOrderService")
public class WorkOrderService extends BaseService implements IWorkOrderService {

	private static final Logger logger = LoggerFactory.getLogger(WorkOrderService.class);

	@Autowired
	activitiClientAPI clientAPI;
	@Autowired
	WorkOrderMapper workOrderMapper;
	@Autowired
	WorkSeatSchedulingService workSeatSchedulingService;
	@Autowired
	WorkCommentService workCommentService;
	@Autowired
	WorkTaskHistoryService workTaskHistoryService;
	@Autowired
	WorkOrderPhotographyMapper workOrderPhotographyMapper;

	/**
	 * 创建工单 <b>Description: 创建工单， 启动流程（在client中创建）</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月20日 下午3:43:42 <br>
	 *       <b>Version:</b> 1.0
	 */
	@Override
	public ResultDO createWorkOrder(WorkOrderDO domain) {
		// 创建工单
		ResultDO result = new ResultSupport();
		// 1.数据验证
		if (isNumberInValid(domain.getOrderID())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("订单id为空");
			result.setSuccess(false);
			return result;
		}

		// 1.写入工单数据
		WorkOrder workOrder = new WorkOrder();
		BeanUtilsExtends.copy(workOrder, domain);

		workOrder.setTaskDefID(TaskDefKey.ORDER_SCHEDULE.getKey()); // 当前任务：预约拍摄
		workOrder.setIsRePhotograph(BonConstant.STATUS_FALSE);
		workOrder.setIsReshot(BonConstant.STATUS_FALSE);
		workOrder.setIsChangeDate(BonConstant.STATUS_FALSE);
		workOrder.setStatus(BonConstant.WORKORDER_STATUS_GOING); // 工单状态：0进行中
		workOrder.setIsDelete(BonConstant.DB_NORMAL);
		workOrder.setCreatetime(Calendar.getInstance().getTime());

		int ret = workOrderMapper.insert(workOrder);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("工单创建失败");
			result.setSuccess(false);
			logger.error("工单创建失败：" + domain.getOrderID());
			return result;
		}

		// 2.启动流程，得到流程ID，更新工单表
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("assignee", domain.getEmployeeName());
		String processInstanceID = clientAPI.startWorkflow(BonConstant.PROCESS_KEY, "test", workOrder.getId() + "",
				variables);
		// 3.更新工单数据
		WorkOrder workOrderUpdate = new WorkOrder();
		workOrderUpdate.setId(workOrder.getId());
		workOrderUpdate.setProcessInstanceID(processInstanceID);
		workOrderMapper.updateByPrimaryKeySelective(workOrderUpdate);

		// 4.写入工单执行备注表、工单任务记录表
		// 执行备注表
		WorkCommentDO commentDO = new WorkCommentDO();
		commentDO.setWorkOrderID(workOrder.getId());
		commentDO.setProcessInstanceID(processInstanceID);
		commentDO.setTaskDefID(TaskDefKey.CREATE_WORKORDER.getKey()); // 创建工单
		commentDO.setTaskName(TaskDefKey.CREATE_WORKORDER.getName());
		commentDO.setType(BonConstant.COMMENT_TYPE_EVENT); // 0备注；1事件
		commentDO.setRemark("创建工单，开始服务流程");
		commentDO.setAuthorID(domain.getAuthorID());
		commentDO.setAuthor(domain.getAuthor());
		workCommentService.add(commentDO);

		// 工单任务记录表
		WorkTaskHistoryDO taskHistoryDO = new WorkTaskHistoryDO();
		taskHistoryDO.setWorkOrderID(workOrder.getId());
		taskHistoryDO.setProcessInstanceID(processInstanceID);
		taskHistoryDO.setTaskDefID(TaskDefKey.CREATE_WORKORDER.getKey()); // 订单上摄控
		taskHistoryDO.setTaskName(TaskDefKey.CREATE_WORKORDER.getName());
		taskHistoryDO.setSchedulingdate(Calendar.getInstance().getTime());
		taskHistoryDO.setEndOn(Calendar.getInstance().getTime());
		taskHistoryDO.setStatus(BonConstant.STATUS_TRUE);
		taskHistoryDO.setAuthorID(domain.getAuthorID());
		taskHistoryDO.setAuthor(domain.getAuthor());
		workTaskHistoryService.add(taskHistoryDO);

		result.setModel(ResultDO.FIRST_MODEL_KEY, workOrder);
		return result;

//		WorkOrder workOrder = new WorkOrder();
//		// 设置下一步任务：订单上摄控
//		workOrder.setTaskDefID(TaskDefKey.ORDER_SCHEDULE.getKey());
//		workOrder.setOrderID(domain.getOrderID());
//		// TODO: 2.查询订单详情接口
//		workOrder.setOrderID(domain.getOrderID());
//		workOrder.setOrderNo("1535018459191793");
//		workOrder.setOrderDetailID(6);
//		workOrder.setOrderProductSceenID(7); // order_detaill.screenId
//		workOrder.setOrderProductSceenName("爱婴上门体验"); // order_detaill.name
//		// TODO: 订单产品分类： 0新生儿照，1满月照；2婴儿照；3孕妈照
//		workOrder.setOrderType(0); //
//		// TODO: 订单产品分类： 10孕妈、12儿童、13新生儿、14婚纱、50全家福、51免费
//		workOrder.setPackageCategory(0); // order_package.categoryId
//		workOrder.setPackageName("爱婴上门体验套餐"); // order_package.name
//		workOrder.setOrderPrice(new BigDecimal(7000)); // order.amout
//		workOrder.setCustomID(5); // order.customerId
//		workOrder.setCustomName("贾小宝"); // family_member
//		workOrder.setTelephone("15922222222"); // family_member
//		workOrder.setProvince("500000"); // contact
//		workOrder.setCity("500100"); // contact
//		workOrder.setDistrict("500103"); // contact
//		workOrder.setAddress("解放碑街道解放碑地下环道重庆医科大学附属第二医院"); // contact
//
//		workOrder.setPlanShotDate(new Date());// 计划拍摄时间 order_scene.shotDate
//		workOrder.setShotHours(2); // 预计拍摄时长 order_scene.shotTime
//		workOrder.setShotRatio(100); // 拍摄比例 order_scene.shotProportion
//		workOrder.setShotSubject(""); // 拍摄主体 order.subject
//		workOrder.setOrderStatus(0); // TODO：0-正常; 1-改期订单; 2-重拍订单; 3-补拍订单 ???
//		workOrder.setRemark(""); // TODO：订单备注
//		workOrder.setStatus(BonConstant.WORKORDER_STATUS_GOING); // 工单状态：0进行中
//		workOrder.setIsDelete(BonConstant.DB_NORMAL);
//		workOrder.setCreatetime(Calendar.getInstance().getTime());
//		workOrder.setEmployeeID(domain.getAuthorID());
//		workOrder.setEmployeeName(domain.getAuthor());
//		workOrder.setIsRePhotograph(BonConstant.STATUS_FALSE);
//		workOrder.setIsReshot(BonConstant.STATUS_FALSE);
//		workOrder.setIsChangeDate(BonConstant.STATUS_FALSE);
//
//		// 3.写入工单表
//		int ret = workOrderMapper.insert(workOrder);
//		if (ret < 1) {
//			result.setErrorCode(ResultDO.PARAM_ERROR);
//			result.setErrorMsg("工单生成失败");
//			result.setSuccess(false);
//			return result;
//		}
//
//		// TODO：4.启动流程，得到流程ID，更新工单表
//		// Map<String, Object> variables = new HashMap<String, Object>();
//		// variables.put("assignee", "test");
//		// String processInstanceID =
//		// clientAPI.startWorkflow(BonConstant.PROCESS_KEY, "test",
//		// workOrder.getId() + "",
//		// null);
//		// String processInstanceID = "";
//		//
//		// // 5.更新工单数据
//		// WorkOrder workOrderUpdate = new WorkOrder();
//		// workOrderUpdate.setId(workOrder.getId());
//		// workOrderUpdate.setProcessInstanceID(processInstanceID);
//		// workOrderMapper.updateByPrimaryKeySelective(workOrderUpdate);
//
//		result.setModel(ResultDO.FIRST_MODEL_KEY, workOrder);
//		return result;
	}

	/**
	 * 查询工单列表 <b>Description:查询</b><br>
	 * 
	 * @param queryDO
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月19日 下午4:10:05 <br>
	 *       <b>Version:</b> 1.0
	 */
	@Override
	public ResultDO query(WorkOrderQueryDO queryDO) {
		ResultDO result = new ResultSupport();

		WorkOrderExample example = new WorkOrderExample();
		WorkOrderExample.Criteria criteria = example.createCriteria();
		// 工单id
		if (!isNumberInValid(queryDO.getId())) {
			criteria.andIdEqualTo(queryDO.getId());
		}
		// 订单id
		if (!isNumberInValid(queryDO.getOrderID())) {
			criteria.andOrderIDEqualTo(queryDO.getOrderID());
		}
		// 场次id
		if (!isNumberInValid(queryDO.getOrderProductSceenID())) {
			criteria.andOrderProductSceenIDEqualTo(queryDO.getOrderProductSceenID());
		}
		// 当前任务
		if (null != queryDO.getTasks() && queryDO.getTasks().size() > 0) {
			criteria.andTaskDefIDIn(queryDO.getTasks());
		}
		// 是否重拍
		if (null != queryDO.getRePhotographList() && queryDO.getRePhotographList().size() > 0) {
			criteria.andIsRePhotographIn(queryDO.getRePhotographList());
		}
		// 是否补拍
		if (null != queryDO.getReshotList() && queryDO.getReshotList().size() > 0) {
			criteria.andIsReshotIn(queryDO.getReshotList());
		}
		// 是否改期
		if (null != queryDO.getChangeDateList() && queryDO.getChangeDateList().size() > 0) {
			criteria.andIsChangeDateIn(queryDO.getChangeDateList());
		}
		// 订单状态
		if (null != queryDO.getOrderStatus() && queryDO.getOrderStatus().size() > 0) {
			criteria.andOrderStatusIn(queryDO.getOrderStatus());
		}
		// 订单类型
		if (null != queryDO.getType()) {
			criteria.andOrderTypeEqualTo(queryDO.getType());
		}
		// 客户姓名/电话
		if (null != queryDO.getNameOrTel()) {
			if (StringUtils.isNumeric(queryDO.getNameOrTel())) {
				criteria.andTelephoneLike("%" + queryDO.getNameOrTel() + "%");
			} else {
				criteria.andCustomNameLike("%" + queryDO.getNameOrTel() + "%");
			}
		}

		if (null == queryDO.getStatus()) {
			// 默认状态：工单状态不等于取消
			criteria.andStatusNotEqualTo(BonConstant.WORKORDER_STATUS_CANCLE);
		} else {
			criteria.andStatusEqualTo(queryDO.getStatus());
		}
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		if (queryDO.isPage()) {
			example.setLimitByPage(queryDO.getStart() + "," + queryDO.getPageRows());
			int count = workOrderMapper.countByExample(example);
			result.setModel(ResultDO.SECOND_MODEL_KEY, count);
		}

		List<WorkOrder> list = workOrderMapper.selectByExample(example);
		result.setModel(ResultDO.FIRST_MODEL_KEY, getWorkOrderDOList(list));

		return result;
	}

	@Override
	public ResultDO edit(WorkOrderDO domain) {

		ResultDO result = new ResultSupport();
		WorkOrder entity = new WorkOrder();

		if (!BeanUtilsExtends.copyProperties(entity, domain)) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("数据转换错误");
			result.setSuccess(false);
			return result;
		}
		WorkOrderExample example = new WorkOrderExample();
		WorkOrderExample.Criteria criteria = example.createCriteria();
		if (!isNumberInValid(domain.getId())) {
			criteria.andIdEqualTo(domain.getId());
		}
		if (!isNumberInValid(domain.getOrderID())) {
			criteria.andOrderIDEqualTo(domain.getOrderID());
		}
		if (StringUtils.isNotEmpty(domain.getProcessInstanceID())) {
			criteria.andProcessInstanceIDEqualTo(domain.getProcessInstanceID());
		}

		entity.setModifitime(Calendar.getInstance().getTime());
		int ret = workOrderMapper.updateByExampleSelective(entity, example);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("更新失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	@Override
	public ResultDO get(Integer id) {

		ResultDO result = new ResultSupport();

		if (isNumberInValid(id)) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}

		WorkOrder workOrder = workOrderMapper.selectByPrimaryKey(id);
		if (null == workOrder || workOrder.getIsDelete() == BonConstant.DB_DELETE) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("工单不存在");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, getWorkOrderDO(workOrder));
		return result;
	}

}
